package MultiNetworkingBase;

/** NoobMarcusHandler.java */

import java.util.ArrayList;

import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;

public class InputHandler {
	
	private ArrayList<Button> buttonList;
	private TextField activeField = null;
	private boolean mouseDown = false;
	
	public InputHandler(ArrayList<Button> buttonList){
		this.buttonList = buttonList;
	}
	
	public InputHandler(){
		this(null);
	}
	
	public void handleKeyboard(WarTug game){
		// First make sure there is something to add text to
		if (activeField != null){
			while (Keyboard.next()){
				if (Keyboard.getEventKeyState()) {
					// Give the typed character to the active TextField
					activeField.addChar(Keyboard.getEventKey(), Keyboard.getEventCharacter());
				}
			}
		} else
			Keyboard.next();
	}
	
	public void handleMouse(){
		// Pressing the left mouse button
		if (!mouseDown && Mouse.isButtonDown(0)){
			boolean textFieldClicked = false;
			mouseDown = true;
			int x = Mouse.getX();
			int y = GraphicsManager.WINDOW_HEIGHT - Mouse.getY(); // Have to invert the y coordinate.  0 is at the bottom...
			//System.out.println("x: " + x + " y: "+ y);
			for (Button b: buttonList){
				// Try to perform a click on each button
				boolean clicked = false;
				if (b.act != null)
					clicked = b.takeClick(x, y);
				// If successfully clicked, then handle the focusing of text fields
				if (clicked && b instanceof TextField){
					activeField = (TextField) b;
					textFieldClicked = true;
				}
			}
			if (!textFieldClicked){
				activeField = null;
			}
		} else if (mouseDown && !Mouse.isButtonDown(0)){
			mouseDown = false;
		}
	}
	
	public ArrayList<Button> getButtonList(){
		return buttonList;
	}
	
	public void setButtonList(ArrayList<Button> newButtons){
		buttonList = newButtons;
	}
	
	public void clearButtonList(){
		buttonList = null;
		activeField = null;
	}
	
	
	
}
